package com.mate.cloud.order.service;

import com.mate.cloud.order.entity.Order;
import com.mate.cloud.order.message.OrderMessage;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.UUID;

@Service
public class OrderService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    // 定义Topic
    private static final String ORDER_TOPIC = "order_topic";

    /**
     * 创建订单并发送消息
     */
    public Order createOrder(String userId, String productId, Integer quantity) {
        // 1. 创建订单
        Order order = Order.builder()
                .orderId(UUID.randomUUID().toString())
                .userId(userId)
                .productId(productId)
                .quantity(quantity)
                .amount(new BigDecimal("99.9").multiply(new BigDecimal(quantity))) // 假设单价99.9
                .status("PENDING")
                .createTime(LocalDate.now())
                .build();

        // 模拟保存订单到数据库
        System.out.println("订单已保存到数据库: " + order);

        // 2. 构建消息
        OrderMessage message = OrderMessage.builder()
                .orderId(order.getOrderId())
                .productId(productId)
                .quantity(quantity)
                .userId(userId)
                .timestamp(System.currentTimeMillis())
                .build();

        // 3. 发送消息到RocketMQ
        rocketMQTemplate.convertAndSend(ORDER_TOPIC, message);
        System.out.println("订单消息已发送到RocketMQ: " + message);

        return order;
    }
}
